package com.wealth.system.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.wealth.system.entity.Corporation;
import com.wealth.system.entity.Role;
import com.wealth.system.entity.User;
import com.wealth.system.repository.CorpDao;
import com.wealth.system.service.ICorpService;
import com.wealth.system.service.IUserService;
import com.wealth.system.service.ShiroUser;

import iaas.enums.StatusEnum;
import iaas.service.impl.BaseServiceImpl;

@Component
public class CorpServiceImpl extends BaseServiceImpl<Corporation> implements ICorpService{
	
	@Autowired
	private CorpDao corpDao;
	@Autowired
	private IUserService userService;

	
	/** ------------------------------- 扩展  ------------------------------*/
	
	@Override
	public boolean unique(String corpname) throws Exception {
		Corporation corp = corpDao.findByName(corpname);
		return (corp==null)?true:false;
	}

	
	@Transactional(readOnly=false)
	@Override
	public void openAccount(Corporation corp, User user) throws Exception {
		
		//保存企业
		corp.setCreator(ShiroUser.getInstance().getUser().getUsername());
		corp.setCreatetime(new Date());
		corp.setStatus(StatusEnum.NORMAL.getValue());
		corpDao.save(corp);
		
		//保存用户
		user.setCreator(ShiroUser.getInstance().getUser().getUsername());
		user.setCreatetime(new Date());
		user.setStatus(StatusEnum.NORMAL.getValue());
		user.setCorp(corp);
		user.getRoleList().add(new Role(2L));//企业管理员角色
		userService.save(user);
	}
	
	
	/**
	 * 编辑企业
	 * 2015-07-15 by chan
	 * ------- 参数说明 ----------
	 * corp 修改企业的名称和起始时间
	 * user 修改企业管理员的密码
	 */
	@Transactional(readOnly=false)
	@Override
	public void updateAccount(Corporation corp, User user) throws Exception {
		
		Corporation temp = corpDao.findOne(corp.getId());
		temp.setName(corp.getName());
		temp.setStarttime(corp.getStarttime());
		temp.setOvertime(corp.getOvertime());
		temp.setTitle(corp.getTitle());
		temp.setContent(corp.getContent());
		temp.setPicurl(corp.getPicurl());
		temp.setUrl(corp.getUrl());
		temp.setShareurl(corp.getShareurl());
		corpDao.save(temp);
		
		userService.updatePassword(user);
	}


	/**
	 *查询状态正常的企业
	 */
	@Override
	public List<Corporation> findByStatus(Integer status) throws Exception {
		
		return corpDao.findByStatus(status);
	}
	
}
